



# --------------------------- ​​策略模式 -------------------------------
class SortStrategy:
    def __call__(self, data):
        raise NotImplementedError

class QuickSort(SortStrategy):
    def __call__(self, data):
        # 快速排序逻辑
        return sorted(data)  

class MergeSort(SortStrategy):
    def __call__(self, data):
        # 归并排序逻辑
        return self._merge_sort(data)  

# 运行时动态选择策略
sorter = QuickSort() if use_fast else MergeSort()
result = sorter([3, 1, 4])  # 统一调用接口



# --------------------------- 单利（元类） -------------------------------
class MetaClass(type):
    def __call__(cls, *args, **kwargs):
        print("拦截实例创建！")
        instance = super().__call__(*args, **kwargs)
        instance.post_init()  # 自动执行后初始化
        return instance

class MyClass(metaclass=MetaClass):
    def post_init(self):
        self.initialized = True

obj = MyClass()  # 输出：拦截实例创建！
    

# --------------------------- 创建延迟计算 -------------------------------
class LazyOperation:
    def __init__(self, func, *args):
        self.func = func
        self.args = args
        self._result = None

    def __call__(self):
        if self._result is None:
            print("执行计算...")
            self._result = self.func(*self.args)
        return self._result

# 创建延迟计算对象（此时未执行）
heavy_calc = LazyOperation(expensive_function, 1000)
# 实际需要结果时才触发计算
result = heavy_calc()  



# --------------------------- 装饰器 -------------------------------
class RetryPolicy:
    def __init__(self, retries=3):
        self.retries = retries

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            for _ in range(self.retries):
                try:
                    return func(*args, **kwargs)
                except Exception:
                    pass
            raise RuntimeError("重试失败")
        return wrapper

@RetryPolicy(retries=5)
def unstable_api():
    # 可能失败的操作
    ...